package com.dhecp.project.hr.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dhecp.common.annotation.Log;
import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.dto.NameValueSelectDto;
import com.dhecp.core.utils.MapUtil;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.api.util.ApiConfig;
import com.dhecp.project.business.domain.ProductActive;
import com.dhecp.project.business.domain.ProductCarefullyChosen;
import com.dhecp.project.business.domain.ProductCarefullySetting;
import com.dhecp.project.business.domain.TysCart;
import com.dhecp.project.business.domain.TysProductDiscount;
import com.dhecp.project.business.mapper.ProductCarefullySettingMapper;
import com.dhecp.project.business.mapper.TysCartMapper;
import com.dhecp.project.business.service.ChoiceShopService;
import com.dhecp.project.business.service.ProductActiveService;
import com.dhecp.project.business.service.ProductCarefullyChosenService;
import com.dhecp.project.business.service.ProductCarefullySettingService;
import com.dhecp.project.business.service.TysProductDiscountService;
import com.dhecp.project.common.controller.BaseModuleController;
import com.dhecp.project.hr.domain.ChoiceShop;
import com.dhecp.project.hr.domain.ProductSetup;
import com.dhecp.project.hr.service.ProductSetupService;
import com.dhecp.project.storage.domain.DeliveryLogistics;
import com.dhecp.project.storage.domain.StockAllot;
import com.dhecp.project.storage.mapper.DeliveryLogisticsDetailMapper;
import com.dhecp.project.storage.mapper.DeliveryLogisticsMapper;
import com.dhecp.project.storage.mapper.StockAllotMapper;
import com.dhecp.project.storage.mapper.StockControlMapper;

import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * @program: kjecp
 * @description: 逸思精品
 * @author: hlf
 * @create: 2022-12-13 13:58
 */
@Controller
@RequestMapping("/hr/choiceshop")
public class ChoiceShopController extends BaseModuleController {

    private String prefix = "hr/choiceshop";
    private String moduleTable = ModuleTable.PRODUCT_ACTIVE;


    @Autowired
    private ChoiceShopService choiceShopService;
    @Autowired
    private ProductActiveService productActiveService;
    @Autowired
    private ProductCarefullyChosenService productCarefullyChosenService;
    @Autowired
    private ProductCarefullySettingService productCarefullySettingService;

    @Autowired
    private DeliveryLogisticsMapper deliveryLogisticsMapper;
    @Autowired
    private DeliveryLogisticsDetailMapper deliveryLogisticsDetailMapper;
    @Autowired
    private ProductCarefullySettingMapper productCarefullySettingMapper;
    @Autowired
    private ProductSetupService productSetupService;
    @Autowired
    private StockAllotMapper stockAllotMapper;
    @Autowired
    private StockControlMapper stockControlMapper;
    @Autowired
    private TysProductDiscountService tysProductDiscountService;
    @Autowired
    private TysCartMapper tysCartMapper;
    


    /**
     * 打开查询列表页
     * @param params
     * @return
     * @author DH-Xxj
     */
    @RequiresPermissions("hr:choiceshop:view")
    @GetMapping()
    public ModelAndView listPage(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        params.put("entity", new ChoiceShop()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("prefix",prefix + "/choiceshop"); //页面路径
        params.put("checkBox", "yes");

        ModelAndView mv = this.openListPage(params);
        mv.addObject("hr", "choiceshop");
        mv.addObject("numProductOnCart", tysCartMapper.countByCreateUserId(ShiroUtils.getUserId()));
        mv.addObject("ali1688AppKey", ApiConfig.getAli1688AppKey());
        mv.addObject("ali1688EcpApiUrl", ApiConfig.getAli1688EcpApiUrl());
        return mv;
    }

    /**
     * 商品设置页面
     */
    @GetMapping("/toSetting")
    public ModelAndView toSetting(String code){

        try{
            ModelAndView mv = new ModelAndView();
            
            ProductSetup productSetup = productSetupService.findByCode(code);
            if (productSetup == null) {
            	productSetup = new ProductSetup();
            	productSetup.setGuid(RandomValueUtils.getGUID());
            	productSetup.setRetailPriceUsa("0");
            	productSetup.setCostUsa(Double.valueOf("0"));
            	productSetup.setGrossMarginUsa(Double.valueOf("0"));
            	productSetup.setCapitalOutoutRatioUsa(Double.valueOf("0"));
            	productSetup.setFloorPriceUsa(Double.valueOf("0"));
            	productSetup.setRetailPriceUk("0");
            	productSetup.setCostUk(Double.valueOf("0"));
            	productSetup.setGrossMarginUk(Double.valueOf("0"));
            	productSetup.setCapitalOutoutRatioUk(Double.valueOf("0"));
            	productSetup.setFloorPriceUk("0");
            	productSetup.setvType("新品");
            	productSetup.setInfo("[]");
            	productSetup.setInfoBase("{}");
            	productSetup.setCreateTime(new Date());
            	productSetup.setUpdateTime(new Date());
            	productSetupService.insert(productSetup);
			}
            List<NameValueSelectDto> vTypeArr = new ArrayList<NameValueSelectDto>();
            {
            	String name = "新品";
            	String value = "新品";
            	boolean isSelected = productSetup.getvType().equals("新品");
            	vTypeArr.add(new NameValueSelectDto(name, value, isSelected));
            }
            {
            	String name = "爆品";
            	String value = "爆品";
            	boolean isSelected = productSetup.getvType().equals("爆品");
            	vTypeArr.add(new NameValueSelectDto(name, value, isSelected));
            }
            {
            	String name = "空";
            	String value = "空";
            	boolean isSelected = productSetup.getvType().equals("空");
            	vTypeArr.add(new NameValueSelectDto(name, value, isSelected));
            }
            
            // 价格阶梯
            JSONArray infoJA = JSON.parseArray(productSetup.getInfo() != null ? productSetup.getInfo() : "[]");
            if (infoJA.size() == 0) {
            	JSONObject infoJO = new JSONObject();
            	infoJO.put("num", 1);
            	infoJO.put("percent", 1);
				infoJA.add(infoJO);
			}
            List<SettingDto.PriceDto> priceArr = new ArrayList<SettingDto.PriceDto>();
            for (int i = 0; i < infoJA.size(); i++) {
            	JSONObject infoJO = infoJA.getJSONObject(i);
            	Integer num = infoJO.getInteger("num");
            	Integer numSecond = infoJO.getInteger("numSecond");
            	String percent = infoJO.getString("percent");
            	String unitName = infoJO.containsKey("unitName") ? infoJO.getString("unitName") : "";
            	priceArr.add(new SettingDto.PriceDto(num, numSecond, percent, unitName));
			}
            
            // 商品详情数组
            List<SettingDto.DetailDto> detailArr = new ArrayList<SettingDto.DetailDto>();
            String pcode = code;
            List<ProductCarefullySetting> listProductCarefullySetting = productCarefullySettingService.listByPcode(pcode);
            if (listProductCarefullySetting != null) {
                for(ProductCarefullySetting productCarefullySetting : listProductCarefullySetting) {
                	String guid = productCarefullySetting.getGuid();
                	String code2 = productCarefullySetting.getCode();
                	String attr = productCarefullySetting.getAttr();
                	String warehouse = productCarefullySetting.getWarehouse();
                	String size = productCarefullySetting.getSize();
                	String weight = productCarefullySetting.getWeight();
                	BigDecimal retailPrice = productCarefullySetting.getRetailPrice();
                	BigDecimal originPrice = productCarefullySetting.getOriginPrice();
                	Integer numPerBox = productCarefullySetting.getNumPerBox();
                	Integer numBuyMin = productCarefullySetting.getNumBuyMin();
                	Integer numBuyMinSecond = productCarefullySetting.getNumBuyMinSecond();
                	String unitName = productCarefullySetting.getUnitName();
                	Integer period = productCarefullySetting.getPeriod();
                	String timeArrivePredict = productCarefullySetting.getTimeArrivePredict();
                	Integer numAll = productCarefullySetting.getNumAll();
                	Integer numPreBuy = productCarefullySetting.getNumPreBuy();
                	detailArr.add(new SettingDto.DetailDto(guid, code2, pcode, attr, warehouse, size, weight, retailPrice, originPrice, numPerBox, numBuyMin, numBuyMinSecond, unitName, period, timeArrivePredict, numAll, numPreBuy));
                }
			}

            String guid = productSetup.getGuid();
            String retailPriceUsa = productSetup.getRetailPriceUsa();
            String costUsa = productSetup.getCostUsa().toString();
            String grossMarginUsa = productSetup.getGrossMarginUsa().toString();
            String capitalOutoutRatioUsa = productSetup.getCapitalOutoutRatioUsa().toString();
            String floorPriceUsa = productSetup.getFloorPriceUsa() != null ? productSetup.getFloorPriceUsa().toString() : "";
            String deliveryFeeUsa = productSetup.getDeliveryFeeUsa().toString();
            String retailPriceUk = productSetup.getRetailPriceUk();
            String costUk = productSetup.getCostUk().toString();
            String grossMarginUk = productSetup.getGrossMarginUk().toString();
            String capitalOutoutRatioUk = productSetup.getCapitalOutoutRatioUk().toString();
            String floorPriceUk = productSetup.getFloorPriceUk() != null ? productSetup.getFloorPriceUk().toString() : "";
            String deliveryFeeUk = productSetup.getDeliveryFeeUk().toString();
            
            JSONObject infoBaseJO = productSetup.getInfoBaseJO();
            String remark = productSetup.getRemark();
            String sizePackage = infoBaseJO.containsKey("sizePackage") ? infoBaseJO.getString("sizePackage") : "";
            String weightPackage = infoBaseJO.containsKey("weightPackage") ? infoBaseJO.getString("weightPackage") : "";
            String advantage = infoBaseJO.containsKey("advantage") ? infoBaseJO.getString("advantage") : "";
            SettingDto dto = new SettingDto(guid, code, retailPriceUsa, costUsa, grossMarginUsa, capitalOutoutRatioUsa, floorPriceUsa, deliveryFeeUsa,
            		retailPriceUk, costUk, grossMarginUk, capitalOutoutRatioUk, floorPriceUk, deliveryFeeUk,
            		remark, sizePackage, weightPackage, advantage,
            		vTypeArr, priceArr, detailArr);
            
            mv.addObject("dto", dto);
            mv.setViewName(prefix + "/choiceshop_setting");
            return mv;
        }catch(Exception e){
        	e.printStackTrace();
            return this.gotoModelAndViewErrorPage(e.getMessage());	//详细信息
        }
    }
    @Data
    @AllArgsConstructor
    public static class SettingDto {
    	private String guid;
    	private String code;
    	private String retailPriceUsa; // 建议售价
    	private String costUsa; // 预算成本
    	private String grossMarginUsa; // 预算毛利率
    	private String capitalOutoutRatioUsa; // 投入产出比
    	private String floorPriceUsa; // 最低售价要求
        private String deliveryFeeUsa;// FBA配送费（美国）
    	private String retailPriceUk; // 建议售价
    	private String costUk; // 预算成本
    	private String grossMarginUk; // 预算毛利率
    	private String capitalOutoutRatioUk; // 投入产出比
    	private String floorPriceUk; // 最低售价要求
        private String deliveryFeeUk;// FBA配送费（英国）
    	private String remark; // 预计到货日期
    	private String sizePackage; // 包装尺寸
    	private String weightPackage; // 包装重量
    	private String advantage; // 商品竞争优势
    	private List<NameValueSelectDto> vTypeArr; // 商品标签
    	private List<PriceDto> priceArr; // 价格数组
    	private List<DetailDto> detailArr; // 商品详情数组

        @Data
        @AllArgsConstructor
        public static class PriceDto {
        	private Integer num; // 首次调拨数量
        	private Integer numSecond; // 再次调拨数量
        	private String percent; //  折扣，如97%，则填写为0.97
        	private String unitName; // 单位名称
        }

        @Data
        @AllArgsConstructor
        public static class DetailDto {
        	private String guid; // 
        	private String code; // 商品编码
        	private String pcode; // 所属精品编码
        	private String attr; // 属性名
        	private String warehouse; // 所在仓库
        	private String size; // 箱规尺寸(cm)
        	private String weight; // 箱规重量(kg)
        	private BigDecimal retailPrice; // 建议售价
        	private BigDecimal originPrice; // 单价
        	private Integer numPerBox; // 单箱数量
        	private Integer numBuyMin; // 首次起订箱数
        	private Integer numBuyMinSecond; // 再次起订箱数
        	private String unitName; // 单位名称
        	private Integer period; // 生产货期
        	private String timeArrivePredict; // 预计到货时间
        	private Integer numAll; // 发货数量
        	private Integer numPreBuy; // 预购数量
        }
    }

    /**
     * 编辑基本信息
     * @param 
     * @return
     * @throws Exception
     * @author DH-Xxj
     */
    @PostMapping("/editSetting")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult editSetting(@RequestParam Map<String, Object> params,
    		String sizePackage, String weightPackage, String advantage) throws Exception {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= productSetupService.editSetting((ProductSetup)MapUtil.mapToObject(params, ProductSetup.class),
            		sizePackage, weightPackage, advantage);
        }catch (Exception e) {
        	e.printStackTrace();
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 获取调货信息
     */
    @PostMapping("/detailData")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult detailData(String pcode) throws Exception {
		/*导入测试
		String infoItems = "[{'vGwMc':'岗位1','vHdRs':'1'},{'vGwMc':'岗位2','vHdRs':'2'}]";
		params.put("infoItems", infoItems);
		*/
        AjaxResult ajaxResult = new AjaxResult();
        try {
            
            // 商品详情数组
            List<SettingDto.DetailDto> detailArr = new ArrayList<SettingDto.DetailDto>();
            List<ProductCarefullySetting> listProductCarefullySetting = productCarefullySettingService.listByPcode(pcode);
            for(ProductCarefullySetting productCarefullySetting : listProductCarefullySetting) {
            	String guid = productCarefullySetting.getGuid();
            	String code2 = productCarefullySetting.getCode();
            	String attr = productCarefullySetting.getAttr();
            	String warehouse = productCarefullySetting.getWarehouse();
            	String size = productCarefullySetting.getSize();
            	String weight = productCarefullySetting.getWeight();
            	BigDecimal retailPrice = productCarefullySetting.getRetailPrice();
            	BigDecimal originPrice = productCarefullySetting.getOriginPrice();
            	Integer numPerBox = productCarefullySetting.getNumPerBox();
            	Integer numBuyMin = productCarefullySetting.getNumBuyMin();
            	Integer numBuyMinSecond = productCarefullySetting.getNumBuyMinSecond();
            	String unitName = productCarefullySetting.getUnitName();
            	Integer period = productCarefullySetting.getPeriod();
            	String timeArrivePredict = productCarefullySetting.getTimeArrivePredict();
            	Integer numAll = productCarefullySetting.getNumAll();
            	Integer numPreBuy = productCarefullySetting.getNumPreBuy();
            	detailArr.add(new SettingDto.DetailDto(guid, code2, pcode, attr, warehouse, size, weight, retailPrice, originPrice, numPerBox, numBuyMin, numBuyMinSecond, unitName, period, timeArrivePredict, numAll, numPreBuy));
            }
            return AjaxResult.success(detailArr);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 商品详细页面
     * @param params
     * @return
     * @author DH-Xxj
     */
    @RequiresPermissions("hr:choiceshop:view")
    @GetMapping("/buy")
    public ModelAndView buy(String code){

        try{

            ProductSetup productSetup = productSetupService.findByCode(code);
            if (productSetup == null) {
            	productSetup = new ProductSetup();
            	productSetup.setProductID(code);
            	productSetup.setGuid(RandomValueUtils.getGUID());
            	productSetup.setInfo("[]");
            	productSetup.setvType("空");
            	productSetup.setFloorPriceUsa(0D);
            	productSetup.setRetailPriceUsa("0");
            	productSetup.setCostUsa(0D);
            	productSetup.setCapitalOutoutRatioUsa(0D);
            	productSetup.setDeliveryFeeUsa(0D);
            	productSetup.setGrossMarginUsa(0D);
            	productSetup.setFloorPriceUk("0");
            	productSetup.setRetailPriceUk("0");
            	productSetup.setCostUk(0D);
            	productSetup.setCapitalOutoutRatioUk(0D);
            	productSetup.setDeliveryFeeUk(0D);
            	productSetup.setGrossMarginUk(0D);
            	productSetup.setOriginPriceRange("尚未设置");
            	productSetup.setInfo("[]");
            	productSetup.setInfoBase("{}");
            	productSetupService.insert(productSetup);
			}
            
            // 价格数组-用于显示
        	List<BuyDto.PriceDto> priceArr = new ArrayList<BuyDto.PriceDto>();
            // 价格数组-用于计算
        	List<BuyDto.PriceDto2> prices = new ArrayList<BuyDto.PriceDto2>();
        	List<TysProductDiscount> listTysProductDiscount = tysProductDiscountService.list();
        	{
        		BigDecimal amount = BigDecimal.ZERO;
				BigDecimal discount = BigDecimal.ONE;
				String condText = "任意数量";
				String percentText = "¥" + productSetup.getOriginPriceRange();
				BigDecimal percent = discount;
				
				priceArr.add(new BuyDto.PriceDto(condText, percentText));
				prices.add(new BuyDto.PriceDto2(amount, percent));
        	}
        	for(TysProductDiscount tysProductDiscount : listTysProductDiscount) {
				
        		BigDecimal amount = tysProductDiscount.getAmount();
				BigDecimal discount = tysProductDiscount.getDiscount();
				String condText = "满" + amount;
				String percentText;
				percentText = discount.multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP).toString() + "%";
				BigDecimal percent = discount;
				
				priceArr.add(new BuyDto.PriceDto(condText, percentText));
				prices.add(new BuyDto.PriceDto2(amount, percent));
        	}
            ProductCarefullyChosen entity = productCarefullyChosenService.findByCode(code);
        	
        	// 合并商品数组
        	List<BuyDto.MergeDto> mergeArr = new ArrayList<BuyDto.MergeDto>();
        	List<ProductCarefullyChosen> listProductCarefullyChosen = productCarefullyChosenService.listByCodeMerge(entity.getCodeMerge());
        	for(ProductCarefullyChosen productCarefullyChosen : listProductCarefullyChosen) {
        		
        		String guid = productCarefullyChosen.getGuid();
        		String code2 = productCarefullyChosen.getCode();
        		String img = productCarefullyChosen.getZt1();
        		String link = "/hr/choiceshop/buy?code=" + productCarefullyChosen.getCode();
        		boolean isSelected = productCarefullyChosen.getCode().equals(entity.getCode());
        		mergeArr.add(new BuyDto.MergeDto(guid, code2, img, link, isSelected));
        	}
        	
        	// 调拨详情数组
        	List<BuyDto.DetailDto> detailArr = new ArrayList<BuyDto.DetailDto>();
            String pcode = code;
            List<ProductCarefullySetting> listProductCarefullySetting = productCarefullySettingService.listByPcode(pcode);
            for(ProductCarefullySetting productCarefullySetting : listProductCarefullySetting) {
            	Long id = productCarefullySetting.getId();
            	String guid = productCarefullySetting.getGuid();
            	String code2 = productCarefullySetting.getCode();
            	String attr = productCarefullySetting.getAttr();
            	String warehouse = productCarefullySetting.getWarehouse();
            	String size = productCarefullySetting.getSize();
            	String weight = productCarefullySetting.getWeight();
            	BigDecimal retailPrice = productCarefullySetting.getRetailPrice();
            	BigDecimal originPrice = productCarefullySetting.getOriginPrice();
            	String unitName = productCarefullySetting.getUnitName();
            	Integer numPerBox = productCarefullySetting.getNumPerBox();
            	// 起订箱数根据首次或再次，进行判断
            	Integer numBuyMin = productCarefullySetting.getNumBuyMin();
            	BigDecimal numAllotSelf = stockAllotMapper.sumAllotAllByCodeAndUserId(code2, ShiroUtils.getUserId());
            	if (numAllotSelf.compareTo(BigDecimal.ZERO) > 0) {
            		numBuyMin = productCarefullySetting.getNumBuyMinSecond();
				}
            	
            	/*
            	 * 库存数量计算规则
            	 * 只统计精品3区的GS0641名下库存数量
            	 */
            	Integer stock = stockControlMapper.sumProductNumByProductCodeAndVGsBmForCalfully(code2, "GS0641", warehouse, "精品3区").intValue();
            	String numAllot = "";
            	String realPrice = "";
            	String totalPrice = "";
            	detailArr.add(new BuyDto.DetailDto(id, guid, code2, pcode, attr, warehouse, size, weight, retailPrice, originPrice, unitName, numPerBox, numBuyMin, stock, numAllot, realPrice, totalPrice));
            }
            
            // 图片数组
            List<String> imgArr1 = new ArrayList<String>();
            {
            	imgArr1.add(entity.getZt2());
            	imgArr1.add(entity.getZt3());
            	imgArr1.add(entity.getCct1());
            	imgArr1.add(entity.getCjt1());
            }
            
            // 图片数组
            List<String> imgArr2 = new ArrayList<String>();
            {
            	imgArr2.add(entity.getCjt2());
            	imgArr2.add(entity.getXjt1());
            	imgArr2.add(entity.getYyt1());
            	imgArr2.add(entity.getYyt2());
            }

            ProductActive productActive = productActiveService.queryProductActiveByCode(code);
            String img = entity.getZt1();
            String name = entity.getName();
            Integer numAllot = stockAllotMapper.sumAllotFinishByCode(code).intValue();
            String material = productActive.getMaterialCn();
            String size = productActive.getSizeLength() + "*" + productActive.getSizeWidth() + "*" + productActive.getSizeHeight();
            String weight = productActive.getSizeWeight() + "";
            String linkJP = productActive.getLinkJP() != null && productActive.getLinkJP().length() > 0 ? productActive.getLinkJP() : "不可售";
            String linkJPUS = productActive.getLinkJPUS() != null && productActive.getLinkJPUS().length() > 0 ? productActive.getLinkJPUS() : "不可售";
            String linkVideo = entity.getVideo1();
            String vtype = productSetup.getvType();
            BuyDto.ProfitDto usa = null;
            {
            	String retailPrice = productSetup.getRetailPriceUsa();
            	String floorPrice = productSetup.getFloorPriceUsa() !=null ? productSetup.getFloorPriceUsa().toString() : "0";
            	String cost = productSetup.getCostUsa() != null ? productSetup.getCostUsa().toString() : "0";
            	String grossMargin = productSetup.getGrossMarginUsa() != null ? productSetup.getGrossMarginUsa().toString() : "0";
            	String capitalOutoutRatio = productSetup.getCapitalOutoutRatioUsa() != null ? productSetup.getCapitalOutoutRatioUsa().toString() : "0";
            	String deliveryFee = productSetup.getDeliveryFeeUsa().toString();
            	usa = new BuyDto.ProfitDto(retailPrice, floorPrice, cost, grossMargin, capitalOutoutRatio, deliveryFee);
            }
            BuyDto.ProfitDto uk = null;
            {
            	String retailPrice = productSetup.getRetailPriceUk();
            	String floorPrice = productSetup.getFloorPriceUk() !=null ? productSetup.getFloorPriceUk().toString() : "0";
            	String cost = productSetup.getCostUk() != null ? productSetup.getCostUk().toString() : "0";
            	String grossMargin = productSetup.getGrossMarginUk() != null ? productSetup.getGrossMarginUk().toString() : "0";
            	String capitalOutoutRatio = productSetup.getCapitalOutoutRatioUk() != null ? productSetup.getCapitalOutoutRatioUk().toString() : "0";
            	String deliveryFee = productSetup.getDeliveryFeeUk().toString();
            	uk = new BuyDto.ProfitDto(retailPrice, floorPrice, cost, grossMargin, capitalOutoutRatio, deliveryFee);
            }
            
            JSONObject infoBaseJO = productSetup.getInfoBaseJO();
            String remark = productSetup.getRemark();
            
            String sizePackage = infoBaseJO.containsKey("sizePackage") ? infoBaseJO.getString("sizePackage") : "--";
            String weightPackage = infoBaseJO.containsKey("weightPackage") ? infoBaseJO.getString("weightPackage") : "--";
            
            String advantage = infoBaseJO.containsKey("advantage") ? infoBaseJO.getString("advantage") : "--";
            
            // 统计购物车条数
            String loginUserId = ShiroUtils.getUserId();
            Integer numProductOnCart = tysCartMapper.countByCreateUserId(loginUserId);
            BuyDto dto = new BuyDto(img, name, code, numAllot, material, size, weight, linkJP, linkJPUS, linkVideo, vtype,
            		remark, sizePackage, weightPackage,
            		usa, uk, priceArr, prices, detailArr, mergeArr, imgArr1, imgArr2, advantage, numProductOnCart);

            ModelAndView mv = new ModelAndView();
            Map<String, Object> extraButton = new HashMap<String, Object>();
            Map<String, Object> params2 = new HashMap<String, Object>();
            params2.put("moduleTable",moduleTable);
            extraButton = checkExtraButton(params2);
            
            // 更多信息按钮的权限
            if (stockAllotMapper.sumAllotAllByCode(pcode).intValue() > 0) {
            	extraButton.put("gdxxbtn", 1);
			}
            
            mv.addObject("dto", dto);
            mv.addObject("extraButton", TypeUtils.mapToJson(extraButton));	//额外的按钮状态
            mv.setViewName(prefix + "/choiceshop_buy");
            return mv;
        }catch(Exception e){
        	e.printStackTrace();
            return this.gotoModelAndViewErrorPage(e.getMessage());	//详细信息
        }
    }
    @Data
    @AllArgsConstructor
    public static class BuyDto {
    	private String img;
    	private String name; // 商品名称
    	private String code; // 商品编码
    	private Integer numAllot; // 历史调拨量
    	private String material; // 商品材质
    	private String size; // 商品尺寸(cm)，如：15.2*9.7*7
    	private String weight; // 商品重量(g)
    	private String linkJP; // 竞品链接(英国)
    	private String linkJPUS; // 竞品链接(美国)
    	private String linkVideo; // 视频链接
    	private String vtype; // 类型，如：新品/爆品
    	private String remark; // 备注
    	private String sizePackage; // 
    	private String weightPackage; // 包装重量
    	private ProfitDto usa; // 美国建议售价最低售价及其分析
    	private ProfitDto uk; // 英国建议售价最低售价及其分析
    	private List<PriceDto> priceArr; // 价格数组，至少一个，最多3个，若不足3个则需补齐3个
    	private List<PriceDto2> prices; // 价格数组，用于计算调拨单价及总价
    	private List<DetailDto> detailArr;
    	private List<MergeDto> mergeArr; // 合并商品数组
    	private List<String> imgArr1; // 图片数组1
    	private List<String> imgArr2; // 图片数组2
    	private String advantage; // 商品竞争优势
    	
    	private Integer numProductOnCart; // 购物车条数

        @Data
        @AllArgsConstructor
        public static class PriceDto {
        	private String condText; // 条件文本，如：满200
        	private String percentText; //  折扣，如：98%
        }

        @Data
        @AllArgsConstructor
        public static class PriceDto2 {
        	private BigDecimal amount; // 总金额
        	private BigDecimal percent; //  如：0.98
        }

        @Data
        @AllArgsConstructor
        public static class ProfitDto {
        	private String retailPrice; // 建议售价
        	private String floorPrice; // 最低售价
        	private String cost; // 成本
        	private String grossMargin; // 预估毛利率
        	private String capitalOutoutRatio; // 预估毛利
        	private String deliveryFee; // FBA配送费
        }

        @Data
        @AllArgsConstructor
        public static class DetailDto {
        	private Long id; // 
        	private String guid; // 
        	private String code; // 商品编码
        	private String pcode; // 所属精品编码
        	private String attr; // 属性名
        	private String warehouse; // 仓库
        	private String size; // 箱规尺寸(cm)
        	private String weight; // 箱规重量(kg)
        	private BigDecimal retailPrice; // 建议售价
        	private BigDecimal originPrice; // 单价
        	private String unitName; // 单位名称
        	private Integer numPerBox; // 单箱数量
        	private Integer numBuyMin; // 起订箱数
        	private Integer stock; // 库存
        	private String numAllot; // 调拨数量
        	private String realPrice; // 调拨单价
        	private String totalPrice; // 调拨总价
        }

        @Data
        @AllArgsConstructor
        public static class MergeDto {
        	private String guid; // 
        	private String code; // 商品编码
        	private String img; // 商品图片
        	private String link; // 链接
        	private boolean isSelected; // 是否选中
        }
    }


    /**
    *@Description: 商品调拨
    *@Param: [params]
    *@return: com.dhecp.common.core.domain.AjaxResult
    *@Author: hlf
    *@date: 2023-02-09 15:34
    */
    @Log(title = "商品调拨", businessType = BusinessType.UPDATE)
    @PostMapping("/commodityAllocation")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult commodityAllocation(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= choiceShopService.commodityAllocation(params);
        }catch (Exception e) {
        	e.printStackTrace();
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 商品设置页面
     */
    @GetMapping("/toCart")
    public ModelAndView toCart(){

        ModelAndView mv = new ModelAndView();
        
        List<ToCartDto.DetailDto> detailArr = new ArrayList<ToCartDto.DetailDto>();
        String loginUserId = ShiroUtils.getUserId();
        List<TysCart> listTysCart = tysCartMapper.listByCreateUserId(loginUserId);
        for(TysCart entity : listTysCart) {
        	ProductCarefullySetting productCarefullySetting = productCarefullySettingMapper.findById(entity.getIdSetting());
        	Long id = entity.getId();
        	String productCode = entity.getProductCode();
        	String productName = entity.getProductName();
        	String attr = null;
        	String warehouse = productCarefullySetting.getWarehouse();
        	Integer numPerBox = entity.getNumPerBox();
        	Integer numBuyMin = entity.getNumBuyMin();
        	Integer numBox = entity.getNumBox();
        	Integer numAllot = entity.getNumAllot();
        	BigDecimal originPrice = entity.getOriginPrice();
        	Integer stock = 0;
        	BigDecimal realPrice = BigDecimal.ZERO;
        	BigDecimal totalPrice = BigDecimal.ZERO;
        	detailArr.add(new ToCartDto.DetailDto(id, productCode, productName, attr, warehouse, numPerBox, numBuyMin, numBox, numAllot, originPrice, stock, realPrice, totalPrice));
        }
        
        // 折扣数组
        List<ToCartDto.DiscountDto> discountArr = new ArrayList<ToCartDto.DiscountDto>();
        {
    		BigDecimal amount = BigDecimal.ZERO;
    		BigDecimal discount = BigDecimal.ONE;
			discountArr.add(new ToCartDto.DiscountDto(amount, discount));
    	}
    	List<TysProductDiscount> listTysProductDiscount = tysProductDiscountService.list();
    	for(TysProductDiscount tysProductDiscount : listTysProductDiscount) {
    		BigDecimal amount = tysProductDiscount.getAmount();
    		BigDecimal discount = tysProductDiscount.getDiscount();
			discountArr.add(new ToCartDto.DiscountDto(amount, discount));
    	}
    	
    	/*
    	 *  价格信息数组
    	 */
        List<ToCartDto.PriceInfoDto> priceInfoArr = new ArrayList<ToCartDto.PriceInfoDto>();
        // 原价
        {
    		String title = "原价";
    		String subTitle = "无限制";
    		priceInfoArr.add(new ToCartDto.PriceInfoDto(title, subTitle));
    	}
    	for(TysProductDiscount tysProductDiscount : listTysProductDiscount) {
    		String title = tysProductDiscount.getDiscount().multiply(new BigDecimal(100)).setScale(0) + "%";
    		String subTitle = "满" + tysProductDiscount.getAmount().setScale(0, BigDecimal.ROUND_HALF_UP);
    		priceInfoArr.add(new ToCartDto.PriceInfoDto(title, subTitle));
    	}
    	
    	BigDecimal totalPrice = BigDecimal.ZERO;
    	Integer totalNum = 1;
        ToCartDto dto = new ToCartDto(totalPrice, totalNum, detailArr, discountArr, priceInfoArr);
        mv.addObject("dto", dto);
        mv.setViewName(prefix + "/choiceshop_cart");
        return mv;
    }
    @Data
    @AllArgsConstructor
    public static class ToCartDto {
    	private BigDecimal totalPrice; //  
    	private Integer totalNum; //  
    	private List<DetailDto> detailArr;
    	private List<DiscountDto> discountArr;
    	private List<PriceInfoDto> priceInfoArr;

        @Data
        @AllArgsConstructor
        public static class DetailDto {
        	private Long id; // 
        	private String productCode; // 商品编码
        	private String productName; // 商品编码
        	private String attr; // 
        	private String warehouse; // 仓库
        	private Integer numPerBox; // 单箱数量
        	private Integer numBuyMin; // 起订箱数
        	private Integer numBox;
        	private Integer numAllot; // 调拨数量
        	private BigDecimal originPrice; // 单价
        	private Integer stock; // 库存
        	private BigDecimal realPrice; // 调拨单价
        	private BigDecimal totalPrice; // 调拨总价
        }

        @Data
        @AllArgsConstructor
        public static class DiscountDto {
        	private BigDecimal amount; // 总金额
        	private BigDecimal discount; //  如：0.98
        }

        @Data
        @AllArgsConstructor
        public static class PriceInfoDto {
        	private String title; // 标题，如：¥16
        	private String subTitle; //  副标题，如：满20000
        }
    }

    /**
    *@Description: 商品加入购物车
    */
    @PostMapping("/addToCart")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult addToCart(
    		String choiceShop,
    		String vGsBm,
    		String vGsJc){
    	
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= choiceShopService.addToCart(choiceShop);
        }catch (Exception e) {
        	e.printStackTrace();
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
    *@Description: 商品移出购物车
    */
    @PostMapping("/removeFromCart")
    @ResponseBody
    public AjaxResult removeFromCart(
    		Long id){
    	
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= choiceShopService.removeFromCart(id);
        }catch (Exception e) {
        	e.printStackTrace();
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }


    /**
     * 查询选品库
     * @param params
     * @return
     * @author DH-Xxj
     */
    @GetMapping("/listCart")
    @ResponseBody
    public TableDataInfo listCart(@RequestParam Map<String, Object> params){
        List<ChoiceShop> list = new ArrayList<ChoiceShop>();
        try {
            list = choiceShopService.queryProductActive(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }


    /**
     * 查询选品库
     * @param params
     * @return
     * @author DH-Xxj
     */
    @GetMapping("/list")
    @RequiresPermissions("hr:choiceshop:list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params){
        List<ChoiceShop> list = new ArrayList<ChoiceShop>();
        try {
            list = choiceShopService.queryProductActive(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }

    /**
     * 查询调拨信息
     * @param params
     * @return
     * @author DH-Xxj
     */
    @GetMapping("/allotList")
    @ResponseBody
    public TableDataInfo allotList(@RequestParam Map<String, Object> params){
        List<StockAllot> list = new ArrayList<StockAllot>();
        try {
            list = choiceShopService.allotList(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }

    /**
     * 货期信息
     */
    @PostMapping("/getPeriodInfo")
    @ResponseBody
    public AjaxResult getPeriodInfo(String guid) {
    	
        ProductCarefullySetting entity = productCarefullySettingMapper.queryFirstByGuid(guid);
        if (entity == null) {
			return AjaxResult.error("数据已经变更，请刷新页面");
		}
        
        // 查出最近
        String productCode = entity.getCode();
        String warehouseAddress = entity.getWarehouse();
        
        // 货期数据，根据预期到货时间值进行判断，若存在预期到货时间，则直接取值，否则取近三条运输中的数据
        String unitName = entity.getUnitName();
        String textArriveTime = "2、" + entity.getWarehouse() + "预计到货时间：";
        if (entity.getTimeArrivePredict() == null || entity.getTimeArrivePredict().length() == 0) {
            List<DeliveryLogistics> listDeliveryLogistics = deliveryLogisticsMapper.listProcessByProductCodeAndWarehouse(productCode, warehouseAddress);
            for (int i = 0; listDeliveryLogistics != null && i < listDeliveryLogistics.size() && i < 3; i++) {
            	DeliveryLogistics deliveryLogistics = listDeliveryLogistics.get(i);
            	String bidLogistics = deliveryLogistics.getBid();
            	textArriveTime = textArriveTime + deliveryLogistics.getTimeArrivePredict() + "(" + deliveryLogisticsDetailMapper.sumByBidAndProductCode(bidLogistics, productCode) + unitName + ")，";
    		}
            if (listDeliveryLogistics == null || listDeliveryLogistics.size() == 0) {
            	textArriveTime = textArriveTime + "--，";
    		}
		} else {
        	textArriveTime = textArriveTime + entity.getTimeArrivePredict() + "(" + entity.getNumAll() + unitName + ")" + "，";
		}
        
        // 预购数量，若数量为0，则取运输中的数量
        Integer numPreBuy = entity.getNumPreBuy();
        if (entity.getNumPreBuy() == null || entity.getNumPreBuy() == 0) {
	        numPreBuy = stockAllotMapper.sumAllotProcessByCodeAndWarehouse(entity.getCode(), warehouseAddress).intValue();
		}
        textArriveTime = textArriveTime + "预购：" + numPreBuy + unitName + "，";
        
        // 总数量
        Integer numAll = entity.getNumAll();
        if (numAll == null || numAll == 0) {
        	numAll = deliveryLogisticsDetailMapper.sumProcessByWarehouseAndProductCode(warehouseAddress, entity.getCode()).intValue();
		}
        // 剩余数量
        Integer numLeft = numAll - numPreBuy;
        textArriveTime = textArriveTime + "剩余：" + numLeft + unitName;
        
        
        String textPeriod = "1、生产货期" + (entity.getPeriod() != null ? entity.getPeriod() : "--") + "天";
        GetPeriodInfoDto dto = new GetPeriodInfoDto(textPeriod, textArriveTime);
        
        return AjaxResult.success(dto);
    }
    @Data
    @AllArgsConstructor
    public static class GetPeriodInfoDto {
    	private String textPeriod; // 生产货期，生产货期XXX天
    	private String textArriveTime; // 预计到货时间文本，格式：福州仓预计到货时间：2023-09-30(15天),2023-09-30(15天),2023-09-30(15天)，预购20套，剩余20套
    }

    /**
     * 删除调货信息
     */
    @PostMapping("/deleteDetail")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult deleteDetail(String guid) throws Exception {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= choiceShopService.deleteDetail(guid);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 批量编辑调货信息
     * @param 
     * @return
     * @throws Exception
     * @author DH-Xxj
     */
    @PostMapping("/editDetailBatch")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult editDetailBatch(String pcode, String detailArr) throws Exception {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= choiceShopService.editDetailBatch(pcode, detailArr);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
}